#!/usr/bin/env node

const { execSync } = require('child_process');
const path = require('path');
const fs = require('fs');

// 构建脚本 - 构建所有模块
const environment = process.argv[2] || 'development';

console.log(`构建环境: ${environment}`);
console.log('开始构建所有模块...\n');

// 获取所有子项目
const packagesDir = path.join(__dirname, '../packages');
const packages = fs.readdirSync(packagesDir).filter(item => {
  const itemPath = path.join(packagesDir, item);
  return fs.statSync(itemPath).isDirectory() && fs.existsSync(path.join(itemPath, 'package.json'));
});

// 构建每个模块
packages.forEach(pkg => {
  const packagePath = path.join(packagesDir, pkg);
  const packageJson = JSON.parse(fs.readFileSync(path.join(packagePath, 'package.json'), 'utf8'));
  
  console.log(`构建模块: ${packageJson.name} (${pkg})`);
  
  try {
    if (packageJson.scripts && packageJson.scripts.build) {
      execSync('pnpm run build', {
        cwd: packagePath,
        stdio: 'inherit',
        shell: true
      });
      console.log(`✓ ${packageJson.name} 构建完成\n`);
    } else {
      console.log(`- ${packageJson.name} 无需构建\n`);
    }
  } catch (error) {
    console.error(`✗ ${packageJson.name} 构建失败:`, error.message);
    process.exit(1);
  }
});

console.log('所有模块构建完成！');

// 创建构建信息文件
const buildInfo = {
  timestamp: new Date().toISOString(),
  environment: environment,
  nodeVersion: process.version,
  packages: packages.map(pkg => {
    const packagePath = path.join(packagesDir, pkg);
    const packageJson = JSON.parse(fs.readFileSync(path.join(packagePath, 'package.json'), 'utf8'));
    return {
      name: packageJson.name,
      version: packageJson.version,
      directory: pkg
    };
  })
};

fs.writeFileSync(
  path.join(__dirname, '..', 'build-info.json'),
  JSON.stringify(buildInfo, null, 2)
);

console.log('构建信息已保存到 build-info.json');

